/**
 * 功能说明：Vue Router 配置，包含导航守卫示例。
 */
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)

const Login = () => import('../views/Login.vue')
const Dashboard = () => import('../views/Dashboard.vue')
const Users = () => import('../views/Users.vue')
const FormDemo = () => import('../views/FormDemo.vue')
const CommDemo = () => import('../views/CommDemo.vue')
const DirectiveDemo = () => import('../views/DirectiveDemo.vue')
const I18nDemo = () => import('../views/I18nDemo.vue')

const router = new Router({
  mode: 'history',
  routes: [
    { path: '/', redirect: '/dashboard' },
    { path: '/login', name: 'login', component: Login },
    { path: '/dashboard', name: 'dashboard', component: Dashboard, meta: { requiresAuth: true } },
    { path: '/users', name: 'users', component: Users, meta: { requiresAuth: true } },
    { path: '/form', name: 'form', component: FormDemo },
    { path: '/comm', name: 'comm', component: CommDemo },
    { path: '/directive', name: 'directive', component: DirectiveDemo },
    { path: '/i18n', name: 'i18n', component: I18nDemo }
  ]
})

// 导航守卫：认证校验
router.beforeEach((to, from, next) => {
  const authed = router.app.$store && router.app.$store.getters['auth/isAuthenticated']
  if (to.matched.some(r => r.meta.requiresAuth) && !authed) {
    next({ path: '/login', query: { redirect: to.fullPath } })
  } else {
    next()
  }
})

export default router

